package com.azt.data.action;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.azt.api.dto.CompanyAddDto;
import com.azt.api.dto.CompanyStatusDto;
import com.azt.api.dto.UserAddDto;
import com.azt.api.model.AjaxJson;
import com.azt.api.model.Pagination;
import com.azt.api.service.PaginationService;
import com.azt.data.permission.MenuPermission;
import com.azt.data.utils.CommonUtil;
import com.azt.data.utils.ExcelExportEntityUtil;
import com.azt.data.utils.Globals;
import com.azt.data.utils.RequestUtils;
import com.azt.provider.mapper.CompanyMapper;
import com.azt.provider.mapper.UserMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.StrUtil;

import net.sf.json.JSONArray;

/**
 * Created by zouheyuan on 2017/4/14.
 */
@Controller
@RequestMapping(value = "/user")
public class UserAction extends BaseAction {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private CompanyMapper companyMapper;
	
	@Autowired
	private PaginationService paginationService;
	
	/**
	 * 用户概览
	 *
	 * @param model
	 * @return
	 */
	@MenuPermission
	@RequestMapping(value = "/overview")
	public String overview(ModelMap model) {

		int userNum = userMapper.selectUserNum();
		int companyNum = userMapper.selectCetCustNum();
		int cenMemberNum = userMapper.selectCenMemberNum();
		int signNum = userMapper.selectSignNum();
		int paNum = userMapper.selectPinganAccount();
		List<Map<String, Object>> hotUsers = userMapper.selectHotTop5();
		model.addAttribute("userNum", userNum);// 注册用户
		model.addAttribute("companyNum", companyNum);// 认证企业
		model.addAttribute("cenMemberNum", cenMemberNum);// 集采供应商
		model.addAttribute("signNum", signNum);// 签约采购商
		model.addAttribute("paNum", paNum);// 签约平安企业
		model.addAttribute("hotUsers", hotUsers);// 活跃用户top5

		return "user/overview";
	}

	/**
	 * 获取用户增长图表数据
	 *
	 * @return
	 */
	@RequestMapping("/getAddUserDate")
	@ResponseBody
	public AjaxJson getAddUserDate() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<UserAddDto> list = userMapper.selectAddUserData(startDate, endDate);
		AjaxJson json = AjaxJson.success();
		json.setObj(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		json.setAttributes(params);
		return json;
	}

	/**
	 * 获取用户增长和企业增长
	 *
	 * @return
	 */
	@RequestMapping("/getAddUserAndCompany")
	@ResponseBody
	public AjaxJson getAddUserAndCompany() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<Map<String, Object>> list = userMapper.selectAddUserAndCompany(startDate, endDate);
		AjaxJson json = AjaxJson.success();
		json.setObj(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		json.setAttributes(params);
		return json;
	}

	/**
	 * 每月注册企业及增长率
	 *
	 * @return
	 */
	@RequestMapping("/getAddCompanyAndRate")
	@ResponseBody
	public AjaxJson getAddCompanyAndRate() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<CompanyAddDto> list = userMapper.selectCompanyData(startDate, endDate);
		AjaxJson json = AjaxJson.success();
		json.setObj(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		json.setAttributes(params);
		return json;
	}

	/**
	 * 各认证企业身份数量情况
	 *
	 * @return
	 */
	@RequestMapping("/getAddCerData")
	@ResponseBody
	public AjaxJson getAddCerData() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<CompanyStatusDto> list = userMapper.selectCerDatas(startDate, endDate);
		AjaxJson json = AjaxJson.success();
		json.setObj(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		json.setAttributes(params);
		return json;
	}

	/**
	 * 获取日PV
	 *
	 * @return
	 */
	@RequestMapping("/getDayPv")
	@ResponseBody
	public AjaxJson getDayPv() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.DATE, -15);
			startDate = sdf.format(c.getTime());
		}
//		List<PvDataDto> list = userMapper.selectDayPV(startDate, endDate);
		List<Map<String , Object>> list = userMapper.selectDayPVNew(startDate, endDate);
		AjaxJson json = AjaxJson.success();
		json.setObj(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		json.setAttributes(params);
		return json;
	}

	/**
	 * 获取日UV
	 *
	 * @return
	 */
	@RequestMapping("/getDayUv")
	@ResponseBody
	public AjaxJson getDayUv() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.DATE, -15);
			startDate = sdf.format(c.getTime());
		}
		List<Map<String , Object>> list = userMapper.selectDayUVNew(startDate, endDate);
		AjaxJson json = AjaxJson.success();
		json.setObj(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		json.setAttributes(params);
		return json;
	}

    /*
     * 认证供应商&采购商&采供双重身份用户总数量
     * @return
     */
    @RequestMapping("/getCompanyPro")
    @ResponseBody
    public List<Map<String , Object>> getCompanyPro() {
        List<Map<String , Object>> list = userMapper.selectCompanyPro();
        return list;
    }


    @RequestMapping("/getEnquiryTopTen")
    @ResponseBody
    public List<Map<String , Object>> getEnquiryTopTen() {
        List<Map<String , Object>> list = userMapper.selectEnquiryTop10();
        return list;
    }


    @RequestMapping("/getBuyPriceTopTen")
    @ResponseBody
    public List<Map<String , Object>> getBuyPriceTopTen() {
        List<Map<String , Object>> list = userMapper.selectBuyPriceTop10();
        return list;
    }


    @RequestMapping("/getPublisTopTen")
    @ResponseBody
    public List<Map<String , Object>> getPublisTopTen() {
        List<Map<String , Object>> list = userMapper.selectPublishProductTop10();
        return list;
    }


	/** 用户明细开始 **/
	@MenuPermission
	@RequestMapping(value = "/userdetail")
	public String userdetail(Integer type, Integer userId,ModelMap model) {
		if (type == null) {
			type = 0;
		}

		model.addAttribute("type", type);
		model.addAttribute("userId", userId);
		model.addAttribute("categorys", userMapper.selectCategroys());
		return "user/usertables";
	}
    
	@ResponseBody
	@RequestMapping(value = "/userdetaildata")
	public JSONObject userdetail(HttpServletRequest request,Integer pageNo, String[] orderBy, Integer type, Integer userId, ModelMap model) {
		//搜索条件
		Map searchMap = RequestUtils.getSearchMap(request);
		JSONObject json = new JSONObject();
		List<Map<String, Object>> selectList=null;
		Page<Object> startPage =null;
		// 列表序号
		if (type == null) {
			type = 0;
		}
		if (type.equals(1)) {
			// 企业列表
			  startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			  selectList = companyMapper.selectCompanyList(searchMap);
		} else if (type.equals(2)) {
			// 企业统计
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = userMapper.selectUserCompanyPerMonth(searchMap);
		} else if (type.equals(3)) {
			//用户登陆记录
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = userMapper.selectUserLogRecord(searchMap);
		} else if (type.equals(4)) {
			//活跃用户
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = userMapper.selectHot(searchMap);
		} else if(type.equals(5)){
			//用户详情记录
			if(userId!=null){
				//如果有选时间
				searchMap.put("so_userId", userId);
				int monthCount=13;
				Date date = null;
				Page<Object> startPage2 =new Page();
				startPage2.setPageNum(pageNo == null ? 1 : pageNo);
				if(searchMap.get("so_startTime")!=null && StringUtils.isNotBlank(searchMap.get("so_startTime").toString())  &&  searchMap.get("so_endTime")!=null && StringUtils.isNotBlank(searchMap.get("so_endTime").toString())){
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
					try {
						Date start = df.parse(searchMap.get("so_startTime").toString());
						Date end = df.parse(searchMap.get("so_endTime").toString());
						date=end;
                        //日期差几个月
						int middleMonth = CommonUtil.getMiddleMonth(start,end);
						if(middleMonth>12){
							middleMonth=12;
						}
						monthCount=middleMonth+1;
						startPage2.setPageSize(Globals.PAGE_SIZE);
						startPage2.setTotal(monthCount);
						startPage=startPage2;
					} catch (ParseException e) {
						e.printStackTrace();
					}
					
				
				}else{
					startPage2.setPageSize(Globals.PAGE_SIZE);
					startPage2.setTotal(monthCount);
					startPage=startPage2;
					date=new Date();
				}
				
				String[] last13Months = CommonUtil.getLastMonths(monthCount+1,1,date);
				List<Map<String, Object>> selectList2=new ArrayList<Map<String, Object>>();
				for(int month=last13Months.length-1;month>0;month--){
					searchMap.put("so_startTime",last13Months[month-1]);
					searchMap.put("so_endTime",last13Months[month]);
					List<Map<String, Object>> selectHot = userMapper.selectHotUserDetail(searchMap);
					selectList2.addAll(selectHot);
				}
				selectList=selectList2;
				if(startPage.getPageNum()==1){
					if(monthCount>=10){
						selectList=selectList.subList(0, Globals.PAGE_SIZE);
					}else{
						selectList=selectList.subList(0, monthCount);
					}
				}else{
					selectList=selectList.subList(Globals.PAGE_SIZE, monthCount);
				}
				
				
			}
		}else if(type.equals(6)){//平安E宝用户
			startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			selectList = userMapper.selectPingAnEb(searchMap);
		}else {
			// 用户列表
			 startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
			 selectList = userMapper.selectUserList(searchMap);
		}
		
		Pagination paginationList = paginationService.getPaginationList(startPage, selectList);
		RequestUtils.MapToModelMap(searchMap, request);
		/*
		 * JsonConfig jsonConfig = new JsonConfig();
		 * jsonConfig.setJsonPropertyFilter(new
		 * net.sf.json.util.PropertyFilter() {
		 *
		 * @Override public boolean apply(Object source, String name, Object
		 * value) { if(value == null){ return true; } return false; } });
		 */
		String jsonString = JSON.toJSONString(paginationList.getList(), CommonUtil.jsonfilter, SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		json.put("draw", paginationList.getPageNo());
		json.put("total", paginationList.getTotalCount());
		json.put("recordsTotal", paginationList.getTotalCount());
		json.put("recordsFiltered", paginationList.getTotalCount());
		return json;
	}
	
	@RequestMapping("/exportUserDetailData")
	public void exportUserDetailData(Integer type,HttpServletRequest request,HttpServletResponse response){
		Workbook exportExcel=null;
		Map searchMap = RequestUtils.getSearchMap(request);
		List<Map<String, Object>> selectList=null;
		String title = ".xls";
		if(type.equals(0)){
			// 用户列表
			  selectList = userMapper.selectUserList(searchMap);
			  exportExcel = ExcelExportUtil.exportExcel(new ExportParams(ExcelExportEntityUtil.USER_DETAIL_TITLE, "用户列表" , "用户列表" )
			            ,ExcelExportEntityUtil.UserEntityList(), selectList);
			  title=ExcelExportEntityUtil.USER_DETAIL_TITLE+"用户列表"+title;
		}else if (type.equals(1)) {
			// 企业列表
			  selectList = companyMapper.selectCompanyList(searchMap);
			  exportExcel = ExcelExportUtil.exportExcel(new ExportParams(ExcelExportEntityUtil.USER_DETAIL_TITLE, "企业列表" , "企业列表" )
			            ,ExcelExportEntityUtil.CompanyListList(), selectList);
			  title=ExcelExportEntityUtil.USER_DETAIL_TITLE+"企业列表"+title;
		} else if (type.equals(2)) {
			// 企业统计
			  selectList = userMapper.selectUserCompanyPerMonth(searchMap);
			  exportExcel = ExcelExportUtil.exportExcel(new ExportParams(ExcelExportEntityUtil.USER_DETAIL_TITLE, "企业统计" , "企业统计" )
			            ,ExcelExportEntityUtil.UserCompanyList(), selectList);
			  title=ExcelExportEntityUtil.USER_DETAIL_TITLE+"企业统计"+title;
		} else if (type.equals(3)) {
			//用户登陆记录
			  selectList = userMapper.selectUserLogRecord(searchMap);
			  exportExcel = ExcelExportUtil.exportExcel(new ExportParams(ExcelExportEntityUtil.USER_DETAIL_TITLE, "用户登陆记录" , "用户登陆记录" )
			            ,ExcelExportEntityUtil.UserLogList(), selectList);
			  title=ExcelExportEntityUtil.USER_DETAIL_TITLE+"用户登陆记录"+title;
		} else if (type.equals(4)) {
			//用户登陆记录
			selectList = userMapper.selectHot(searchMap);
			exportExcel = ExcelExportUtil.exportExcel(new ExportParams("活跃度排行", null , "活跃度排行" )
					,ExcelExportEntityUtil.HotList(), selectList);
			title="安装通活跃用户排行"+title;
		}else if(type.equals(6)){
			selectList = userMapper.selectPingAnEb(searchMap);
			exportExcel = ExcelExportUtil.exportExcel(new ExportParams("平安易宝用户", null , "平安易宝用户" )
					,ExcelExportEntityUtil.PingAnEbList(), selectList);
			 title=ExcelExportEntityUtil.USER_DETAIL_TITLE+"平安易宝用户"+title;
		}

		try {
	        response.setContentType("application/vnd.ms-excel;");
	        response.setHeader("Content-Disposition", "attachment;filename="+CommonUtil.toUtf8String(request.getHeader("User-Agent") , title));
			ServletOutputStream outputStream = response.getOutputStream();
			exportExcel.write(outputStream);
			outputStream.flush();  
			outputStream.close(); 
		} catch (IOException e) {
			e.printStackTrace();
		}
	  
	}    
	

//	/** 用户明细结束 **/
//    @RequestMapping("/getAddUserTableJson")
//    @ResponseBody
//    public List<Map<String , Object>> getAddUserTableJson() {
//        String startDate = getPara("startDate");
//        String endDate = getPara("endDate");
//        Calendar c = Calendar.getInstance();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//        if (StrUtil.isBlank(startDate)) {
//            endDate = sdf.format(c.getTime());
//            c.add(Calendar.MONTH , -11);
//            startDate = sdf.format(c.getTime());
//        }
//        List<Map<String, Object>> list = userMapper.selectAddUserData(startDate , endDate);
//        for (int i = 0 ; i < list.size() ; i ++ ) {
//            Map<String, Object> um = list.get(i);
//            um.put("xuhao", i + 1);
//        }
//
//        return list;
//
//    }

    /**
     * 各类供应商占比
     * @return
     */
    @RequestMapping("/getCategoryCompany")
    @ResponseBody
    public List<Map<String , Object>> getCategoryCompany() {
        List<Map<String, Object>> list = userMapper.selectCategoryCompany();
        return list;

    }


    /**
     * 全国企业分布
     * @return
     */
    @RequestMapping("/getMapForCompany")
    @ResponseBody
    public List<Map<String , Object>> getMapForCompany() {
        List<Map<String, Object>> list = userMapper.selectChinaMapForCompany();
        int max = 0;
        for (Map<String, Object> um : list) {
            String name = um.get("name").toString();
            int subEnd = 2;
            if (name.contains("黑龙江") || name.contains("内蒙古")) {
                subEnd = 3;
            }
            name = name.substring(0, subEnd);
            um.put("name", name);
            int v = Integer.parseInt(um.get("value").toString());
            if (v > max) {
                max = v;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("name", "南海诸岛");
        map.put("value", 0);
        list.add(map);
        map.clear();
        map.put("max", max);
        list.add(map);
        return list;

    }

}
